package cn.com.surker.production.controller;

import cn.com.surker.baidu.ai.HttpUtil;
import cn.com.surker.base.pump.service.CastModeService;
import cn.com.surker.base.pump.service.PumpNormService;
import cn.com.surker.base.pump.service.PumpTypeService;
import cn.com.surker.base.strength.entity.BaseStrength;
import cn.com.surker.base.strength.entity.BaseStrengthLevel;
import cn.com.surker.base.strength.service.StrengthBaseService;
import cn.com.surker.base.strength.service.StrengthLevelBaseService;
import cn.com.surker.cache.MemoryCache;
import cn.com.surker.common.AbstractController;
import cn.com.surker.common.Code;
import cn.com.surker.common.HttpRequestHelper;
import cn.com.surker.enums.StateEnum;
import cn.com.surker.enums.production.invoice.InvoiceProcessEnum;
import cn.com.surker.enums.sale.ContractBillTypeEnum;
import cn.com.surker.enums.sale.ContractQualityEnum;
import cn.com.surker.enums.sale.ContractWorkStatusEnum;
import cn.com.surker.lab.service.LabExpendUploadLineService;
import cn.com.surker.lab.service.LabExpendUploadService;
import cn.com.surker.production.entity.ProductionInvoice;
import cn.com.surker.production.service.*;
import cn.com.surker.sale.entity.SaleContract;
import cn.com.surker.sale.service.SaleContractBaseService;
import cn.com.surker.spring.RestResultDto;
import cn.com.surker.util.MathUtils;
import cn.com.surker.weight.service.ErpWeightOrderService;
import cn.com.surker.workcon.service.TaskService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;

/**
 * 生产相关基础类
 *
 * @author luotao
 * @date 2024/9/4
 */
public abstract class ProBaseController extends AbstractController {

	@Autowired
	protected SaleContractBaseService saleContractService;
	@Resource
	protected StrengthBaseService strengthService;
	@Resource
	protected StrengthLevelBaseService strengthLevelService;
	@Resource
	protected CastModeService castModeService;
	@Resource
	protected PumpDeviceService pumpDeviceService;
	@Resource
	protected PumpConDeviceService pumpConDeviceService;
	@Autowired
	protected TranConCarService tranConCarService;

	@Resource
	protected ErpIndentService indentService;
	@Resource
	protected PumpTypeService pumpTypeService;
	@Resource
	protected PumpNormService pumpNormService;
	@Resource
	protected ErpIndentPumpService indentPumpService;
	@Resource
	protected ErpIndentDispatchService indentDispatchService;
	@Resource
	protected ErpInvoiceService invoiceService;
	@Resource
	protected LabExpendUploadService labUploadService;
	@Resource
	protected TranCarService tranCarService;
	//	退剩转操作记录
	@Autowired
	protected ErpInvoiceHandleService invoiceHandleService;
	@Autowired
	protected ErpWeightOrderService erpWeightOrderService;

	@Autowired
	protected TaskService bcsTaskService;

	@Value("${oa.url}")
	protected String oaUrl;

	//	缓存类
	protected MemoryCache memoryCache = MemoryCache.getInstance();



	/**
	 * 验证合同是否可以生产
	 *
	 * @param conId    合同id
	 * @param stere        方量
	 * @return
	 */
	protected RestResultDto validateConPro(Long conId, Long strengthId, Double stere) {
		//	验证合同
		SaleContract contract = saleContractService.getById(conId);
		if (contract == null || !StateEnum.ENABLED.getCode().equals(contract.getStatus())) {
			return RestResultDto.fail(Code.CONTRACT_EMPTY);
		}
		//	验证合同供应状态
		Integer conWorkStatus = contract.getWorkStatus();
		if (conWorkStatus == null) {
			return RestResultDto.fail("合同供应状态不明确,禁止操作");
		}
		if (ContractWorkStatusEnum.DSQ.getCode().equals(conWorkStatus)) {
			return RestResultDto.fail("合同已停供");
		}
		if (ContractWorkStatusEnum.YZZ.getCode().equals(conWorkStatus)) {
			return RestResultDto.fail("合同已终止");
		}
		//	验证方量
		////	总方量
		Double sumStere = contract.getSumStere();
		////	已发货方量
		Double conSendStere = invoiceService.queryConSendStere(erpDb, conId);
		//	查询退回方量
		Double conBakStere = invoiceService.queryConBakStere(erpDb, conId);
		//	发货方量扣除施工方退回方量
		conSendStere = MathUtils.subtract(conSendStere, conBakStere);
		//	剩余方量
		Double surStere = MathUtils.subtract(sumStere, conSendStere);
		if (surStere < stere) {
			//	剩余方量不足
			return RestResultDto.fail("剩余方量已经小于待生产方量,不能操作(总方量:" + sumStere + ";已发货方量:" + conSendStere + ";待生产方量:" + stere + ")");
		}
		boolean a = true;
		if (a) {
			return RestResultDto.success(contract);
		}
		/**
		 * 结算类型类型
		 * 	0:月结					按照结算周期进行计算
		 * 	1:先款后货				欠款就停
		 * 	2:垫资					签订日超过60天或者产值超过30w则停供
		 */
		final Integer billType = contract.getBillType();
		/**
		 *	性质(1:正式2:临时,3零星)ContractQualityEnum
		 */
		final Integer conQualityType = contract.getQuality();
		//	如果剩余方量充足,则判断合同是否先款后货和零星合同,如果是先款后货,则还需要判断金额
		if (ContractBillTypeEnum.XKHH.getCode().equals(billType) || ContractQualityEnum.LXHT.getCode().equals(conQualityType)) {
			//	查询云端数据
			try {
				String params = "token=swgesYkrgcBI8O0dMg03mcZ4ky1jKiWhqD9QArYK3A=&orgId=" + orgId + "&conId=" + conId + "&strengthId=" + strengthId + "&proStere=" + stere;
				String s = HttpUtil.post(oaUrl + "/common/api/sale/credit2", params);
				RestResultDto res = JSONObject.parseObject(s, RestResultDto.class);
				int code = res.getCode();
				if (code == 0) {
					//	操作成功
					return RestResultDto.success(contract);
				} else {
					return RestResultDto.success(-2, "云端验证失败:" + res.getMsg());
				}
			} catch (Exception e) {
				e.printStackTrace();
				//	允许生产
				return RestResultDto.success(contract);
			}
		}
		return RestResultDto.success(contract);
	}

	/**
	 * 将该车辆的发货单置为完成
	 *
	 * @param carId
	 */
	protected void compInvByCar(Long carId) {
		if (carId == null) {
			return;
		}
		UpdateWrapper<ProductionInvoice> uw = new UpdateWrapper<>();
		uw.eq("status", StateEnum.ENABLED.getCode());
		uw.eq("org_id", orgId);
		uw.eq("car_id", carId);
		uw.set("process", InvoiceProcessEnum.TRAN_COMPLETE.getCode());
		invoiceService.update(null, uw);
	}

	/**
	 * 验证标号是否降级
	 *
	 * @param oldStrengthId
	 * @param newStrengthId
	 * @return
	 */
	protected boolean strengthLower(Long oldStrengthId, Long newStrengthId) {
		if (oldStrengthId == null || newStrengthId == null) {
			return false;
		}
		if (oldStrengthId.equals(newStrengthId)) {
			return true;
		}
		//	查询标号信息
		BaseStrength oldStrength = strengthService.getById(oldStrengthId);
		if (oldStrength == null) {
			return false;
		}
		BaseStrength newStrength = strengthService.getById(newStrengthId);
		if (newStrength == null) {
			return false;
		}
		//	判断新标号是否降级
		try {
			//	查询老标号
			Long oldLevelId = oldStrength.getLevelId();
			QueryWrapper qwOld = new QueryWrapper();
			qwOld.eq("status", StateEnum.ENABLED.getCode());
			qwOld.eq("strength_id", oldLevelId);
			qwOld.last("limit 1");
			BaseStrengthLevel oldBase = strengthLevelService.getOne(qwOld);
			Integer oldSort = oldBase.getSort();
			//	查询新标号
			Long newLevelId = newStrength.getLevelId();
			QueryWrapper qwNew = new QueryWrapper();
			qwNew.eq("status", StateEnum.ENABLED.getCode());
			qwNew.eq("strength_id", newLevelId);
			qwNew.last("limit 1");
			BaseStrengthLevel newBase = strengthLevelService.getOne(qwNew);
			Integer newSort = newBase.getSort();
			if (oldSort >= newSort) {
				//	降级了
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}


}
